package com.abocode.aichat.client;

import com.abocode.aichat.data.MessageStanza;
import com.abocode.aichat.data.MessageStanzaImpl;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author guanxf
 */
public class TcpClientHandler extends SimpleChannelInboundHandler<String> {

    Log log = LogFactory.getLog(TcpClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("channelRead0" + msg);
        MessageStanza messageStanza= JSON.parseObject(msg, MessageStanzaImpl.class);
        ModuleServiceFactory.getModuleService(messageStanza.name()).respond(messageStanza.body());
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        log.info("channelRegistered");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        log.info("channelUnregistered");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.info("exceptionCaught:" + cause.getMessage());
    }
}